import axios from "axios";
import { BASE_URL, TIMEOUT } from "./config";
import useMainStore from "@/store/modules/main.js";

const mainStore = useMainStore();

class HYRequest {
  constructor(baseUrl, timeout = 10000) {
    this.instance = axios.create({
      baseUrl,
      timeout,
    });
    // 1 添加所有的实例都有的拦截器(全局)

    this.instance.interceptors.request.use((config)=>{

      mainStore.isLoading = true
      return config
    },err =>{
      return err
    })
    this.instance.interceptors.response.use((res)=>{
      mainStore.isLoading = false
      return res
    },err =>{
      mainStore.isLoading = false
      return err
    })
  }
  request(config) {
    return new Promise((resolve, reject) => {
      this.instance
        .request(config)
        .then((res) => {
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  get(config) {
    return this.request({ ...config, method: "get" });
  }
  post(config) {
    return this.request({ ...config, method: "post" });
  }
}

export default new HYRequest(BASE_URL, TIMEOUT);
